package cc.idoone.spring_boot_hello.mongodb.myconfig;

import com.mongodb.MongoClientURI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * @author hemj
 * @since 2017/10/21
 */
@Configuration
// for JPA
@EnableMongoRepositories(basePackages = "cc.idoone.spring_boot_hello.mongodb.myconfig.secondary",
		mongoTemplateRef = SecondaryMongoConfig.MONGO_TEMPLATE)
public class SecondaryMongoConfig {

	protected static final String MONGO_TEMPLATE = "secondaryMongoTemplate";

	@Autowired
	private MultipleMongoProperties mongoProperties;

	@Bean
	@Qualifier(SecondaryMongoConfig.MONGO_TEMPLATE)
	public MongoTemplate secondaryMongoTemplate() throws Exception {
		return new MongoTemplate(secondaryFactory());
	}

	@Bean
	public MongoDbFactory secondaryFactory() throws Exception {
		MongoProperties mongo = mongoProperties.getSecondary();
		return new SimpleMongoDbFactory(new MongoClientURI(mongo.getUri()));
	}
}
